Print a Christmas tree in JavaScript


Posted by Christy on 2023-01-20

Description: Write a function named tree that accepts an number n and print a Christmas tree with the following patterns

tree(1)
*

tree(5)
    *
   ***
  *****
 *******
*********
    *
    *
    *
    *
    *
function tree(n) {
  if (n === 1) return console.log("*");
  // tree
  for (let i = 1; i <= n; i++) {
    console.log(" ".repeat(n - i) + "*".repeat(2 * i - 1));
  }

  // trunk
  for (let i = 1; i <= n; i++) {
    console.log(" ".repeat(n - 1) + "*");
  }
}

tree(5);









Related Posts

1789. Primary Department for Each Employee

1789. Primary Department for Each Employee

JavaScript 核心 - 你其實已經用過閉包(closure)

JavaScript 核心 - 你其實已經用過閉包(closure)

當我們在 Google 搜尋時,發生了甚麼事?

當我們在 Google 搜尋時,發生了甚麼事?


Comments